package com.example.filepersistencetest.SQLiteUtil

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import android.util.Log

/**
 * 这里是与 ContentResolverTest联动的内容
 * 在此提供数据接口，在那边获取
 */
class DataBaseProvider : ContentProvider() {

    private val bookDir = 0
    private val bookItem = 1
    private val categoryDir = 2
    private val categoryItem = 3
    private val authority = "com.example.database.provider"
    private var dbHelper : MyDatabaseHelper? = null

    private val uriMatcher by lazy {
        val matcher = UriMatcher(UriMatcher.NO_MATCH)
        matcher.addURI(authority,"book",bookDir)
        matcher.addURI(authority,"book/#",bookItem)
        matcher.addURI(authority,"category",categoryDir)
        matcher.addURI(authority,"category/#",categoryItem)
        matcher
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?)=dbHelper?.let {
        val db = it.writableDatabase
        val deletedRows = when(uriMatcher.match(uri)){
            bookDir -> db.delete("Book",selection,selectionArgs)
            bookItem -> {
                //分段中第二段，第一段匹配了
                val bookId = uri.pathSegments[1]
                db.delete("Book","id = ?", arrayOf(bookId))
            }
            categoryDir -> db.delete("Category",selection,selectionArgs)
            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.delete("Category","id = ?", arrayOf(categoryId))
            }
            else -> null
        }
        //返回更新的行
        deletedRows
    }?:0

    override fun getType(uri: Uri) = when(uriMatcher.match(uri)){
        bookDir->       "vnd.android,cursor.dir/vnd.com.example.filepersistencetest.provider.book"
        bookItem->      "vnd.android,cursor.item/vnd.com.example.filepersistencetest.provider.book"
        categoryDir->   "vnd.android,cursor.dir/vnd.com.example.filepersistencetest.provider.category"
        categoryItem->  "vnd.android,cursor.item/vnd.com.example.filepersistencetest.provider.category"
        else->null
    }

    override fun insert(uri: Uri, values: ContentValues?) = dbHelper?.let {
        val db = it.readableDatabase
        val uriReturn = when(uriMatcher.match(uri)){
            bookDir,bookItem -> {
                val newBookId = db.insert("Book",null,values)
                Uri.parse("content://$authority/book/$newBookId")
            }
            categoryDir ,categoryItem -> {
                val newCategoryId = db.insert("Category",null,values)
                Uri.parse("content://$authority/category/$newCategoryId") }
            else -> null
        }
        uriReturn
    }

    override fun onCreate() = context?.let {
        //创建成功返回true 不成功报错let执行返回null 外层？后返回false
        dbHelper = MyDatabaseHelper(it,"BookStore.db",2)
        Log.e("DataBaseProvider", "onCreate: provider启动成功" )
        true
    } ?:false

    override fun query(
        uri: Uri, projection: Array<String>?, selection: String?,
        selectionArgs: Array<String>?, sortOrder: String?
    ) = dbHelper?.let{
        val db = it.readableDatabase
        val cursor = when(uriMatcher.match(uri)){
            bookDir -> db.query("Book",projection,selection,selectionArgs,null,null,sortOrder)
            bookItem -> {
                //分段中第二段，第一段匹配了
                val bookId = uri.pathSegments[1]
                db.query("Book", projection,"id = ?", arrayOf(bookId), null, null, sortOrder)
            }
            categoryDir -> db.query("Category",projection,selection,selectionArgs,null,null,sortOrder)
            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.query("Category", projection,"id = ?", arrayOf(categoryId), null, null, sortOrder)
            }
            else -> null
        }
        //返回值
        cursor
    }

    override fun update(
        uri: Uri, values: ContentValues?, selection: String?,
        selectionArgs: Array<String>?
    ) = dbHelper?.let {
        val db = it.readableDatabase
        val updatedRows = when(uriMatcher.match(uri)){
            bookDir -> db.update("Book",values,selection,selectionArgs)
            bookItem -> {
                //分段中第二段，第一段匹配了
                val bookId = uri.pathSegments[1]
                db.update("Book", values,"id = ?", arrayOf(bookId))
            }
            categoryDir -> db.update("Category",values,selection,selectionArgs)
            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.update("Category", values,"id = ?", arrayOf(categoryId))
            }
            else -> null
        }
        //返回更新的行
        updatedRows
    }?:0    //没有返回0
}